// miniprogram/pages/recipeDetail/recipeDetail.js
import { getRecipeDetail, deleteRecipe } from '../../api/recipes';
import { addFavorite, removeFavorite, checkFavorite } from '../../api/favorite';
import { followAuthor, unFollowAuthor, checkFollow } from '../../api/user'; // 引入关注相关API
import { getCommentsByRecipeId, getRepliesByCommentId, addComment, deleteComment, like, unlike, getLikeStatus, getLikeCount } from '../../api/comment'; // 引入评论相关API
import { store } from '../../utils/store'; // 假设你有一个store来管理用户信息

const app = getApp(); // 获取 app.js 的实例

Page({
  data: {
    recipeInfo: {},
    recipeId: null,
    userId: null, // 存储userId
    isOwner: false,
    authorSectionFixed: false,
    isInList: false,
    showBasketIcon: false,
    isFavorite: false, // 表示是否已收藏
    showLoginModal: false, // 控制登录模态框的显示
    isFollowing: false, // 表示是否已关注作者
    comments: [], // 评论列表数据
    commentText: '', // 评论内容
    replyToId: null, // 回复的评论ID
    replyToUserId: null, // 被回复用户ID
    replyToUsername: '', // 添加被回复用户名称
    isReplyToParent: true, // 默认回复父级评论
    isLoggedIn: false, // 添加登录状态标记

  },

  async onLoad (options) {
    const recipeId = options.recipeId;
    this.setData({ recipeId });
    // 先获取菜谱详情，不阻塞页面加载
    this.fetchRecipeDetail(recipeId);
    this.checkIfInBasket(recipeId);
    this.checkLoginStatus()
    this.initializeUserState(); // 初始化用户状态

    this.createObserver();
    this.fetchComments(recipeId); // 获取评论列表
  },

  onShow () {
    console.log("recpiesdetail onshow执行了");
    const { recipeId } = this.data;
    if (recipeId) {
      // 检查是否有编辑成功的标记
      const editSuccess = wx.getStorageSync('recipeEditSuccess');
      if (editSuccess && editSuccess.recipeId === recipeId) {
        console.log("检测到编辑成功标记，重新获取食谱详情");
        // 清除标记
        wx.removeStorageSync('recipeEditSuccess');
        // 重新获取食谱详情
        this.fetchRecipeDetail(recipeId);
        // 显示修改成功提示
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        });
      }
      this.checkIfInBasket(recipeId);
    }
  },
  // 检查登录状态
  checkLoginStatus () {
    const userInfo = store.getUserInfo();
    if (userInfo && userInfo.userId) {
      this.setData({
        isLoggedIn: true,
        showLoginModal: false,
        userId: userInfo.userId,
        userInfo: userInfo
      });
    } else {
      this.setData({
        isLoggedIn: false,
        userId: null,
        userInfo: null
      });
    }
  },
  scrollToComments () {
    wx.pageScrollTo({
      selector: '.comments-section',
      duration: 100
    });
  },
  // 获取菜谱详情
  async fetchRecipeDetail (recipeId) {
    try {
      const res = await getRecipeDetail(recipeId);
      if (res.success) {
        const userInfo = wx.getStorageSync('userInfo');
        // 判断是否为作者
        const isOwner = userInfo && userInfo.userId === res.data.authorId;
        this.setData({
          recipeInfo: res.data,
          isOwner: isOwner
        });
        // 只有登录状态才检查是否关注
        if (userInfo && userInfo.userId) {
          this.checkIfFollowing(userInfo.userId, res.data.authorId);// 检查是否已关注作者
        }
      } else {
        wx.showToast({
          title: res.message || '获取菜谱详情失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取菜谱详情失败:', error);
      wx.showToast({
        title: '获取菜谱详情失败',
        icon: 'none'
      });
    }
  },

  previewImage () {
    wx.previewImage({
      urls: [this.data.recipeInfo.coverUrl]
    });
  },

  previewStepImage (e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url]
    });
  },

  createObserver () {
    // 实现滚动事件监听逻辑
  },
  //菜篮子
  checkIfInBasket (recipeId) {
    const list = wx.getStorageSync('ingredientList') || [];
    const isInList = list.some(item => item.recipeId === recipeId);
    console.log("isInList", isInList);
    this.setData({
      isInList,
      showBasketIcon: isInList
    });
  },

  toggleList () {
    const isInList = !this.data.isInList;
    this.setData({
      isInList: isInList,
      showBasketIcon: isInList
    });

    if (isInList) {
      this.addToLocalList();
      wx.showToast({
        title: '用料已加入清单',
        icon: 'success'
      });
    } else {
      this.removeFromLocalList();
      wx.showToast({
        title: '用料已从清单中移除',
        icon: 'success'
      });
    }
  },

  addToLocalList () {
    const { recipeId, title, ingredients } = this.data.recipeInfo;
    const list = wx.getStorageSync('ingredientList') || [];

    // 遍历 ingredients，给每个食材加上 completed 字段
    const updatedIngredients = ingredients.map(item => ({
      ...item,      // 保留原有的食材信息
      completed: false  // 默认未完成
    }));

    // 将菜谱的标题和带有 completed 字段的食材信息加入列表
    list.push({ recipeId, title, ingredients: updatedIngredients });

    // 保存到本地存储
    wx.setStorageSync('ingredientList', list);
  },

  removeFromLocalList () {
    const { recipeId } = this.data.recipeInfo;
    let list = wx.getStorageSync('ingredientList') || [];
    list = list.filter(item => item.recipeId !== recipeId);
    wx.setStorageSync('ingredientList', list);
  },

  openBasket () {
    wx.navigateTo({
      url: '/pages/my/myBasket/myBasket'
    });
  },

  // 初始化用户状态
  initializeUserState () {
    const userInfo = store.getUserInfo();
    if (userInfo && userInfo.userId) {
      this.setData({
        isLoggedIn: true,
        userId: userInfo.userId,
        userInfo: userInfo // 设置用户信息用于显示头像
      });
      this.checkIfFavorite(this.data.recipeId); // 检查是否已收藏
    } else {
      // 未登录状态
      this.setData({
        isLoggedIn: false,
        userId: null,
        userInfo: null,
        isFavorite: false, // 未登录默认未收藏
        isFollowing: false // 未登录默认未关注
      });
    }
  },
  // 检查是否已收藏
  async checkIfFavorite (recipeId) {
    const { userId } = this.data;
    try {
      const res = await checkFavorite({ userId, recipeId });
      if (res && res.data) {
        this.setData({ isFavorite: res.data });
      }
    } catch (error) {
      console.error('检查收藏状态失败:', error);
    }
  },
  handleFavorite () {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }

    const { recipeId, isFavorite, userId } = this.data;
    if (isFavorite) {
      removeFavorite({ userId, recipeId }).then(() => {
        this.setData({ isFavorite: false });
        wx.showToast({
          title: '已取消收藏',
          icon: 'success'
        });
      }).catch(err => {
        wx.showToast({
          title: '取消收藏失败',
          icon: 'none'
        });
      });
    } else {
      addFavorite({ userId, recipeId }).then(() => {
        this.setData({ isFavorite: true });
        wx.showToast({
          title: '已收藏',
          icon: 'success'
        });
      }).catch(err => {
        wx.showToast({
          title: '收藏失败',
          icon: 'none'
        });
      });
    }
  },
  // 登录成功回调
  onLoginSuccess () {
    console.log('登录成功huidiao1111');

    // 获取登录成功返回的用户信息
    const userInfo = store.getUserInfo();

    this.setData({
      showLoginModal: false,
      isLoggedIn: true,
      userId: userInfo.userId || userInfo.id,
      userInfo: userInfo
    });

    // 重新获取菜谱详情（确保作者状态正确）
    this.fetchRecipeDetail(this.data.recipeId);

    // 重新检查收藏状态
    this.checkIfFavorite(this.data.recipeId);

    // 重新检查关注状态
    if (this.data.recipeInfo && this.data.recipeInfo.authorId) {
      this.checkIfFollowing(userInfo.userId || userInfo.id, this.data.recipeInfo.authorId);
    }
    // 重新检查是否在购物清单中
    this.checkIfInBasket(this.data.recipeId);
    // 重新获取评论列表和点赞状态
    this.setData({
      comments: [], // 清空评论列表，强制重新加载
      current: 1
    });
    // 重新获取评论点赞状态
    this.fetchComments(this.data.recipeId);

    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });

  },

  // 关闭登录模态框
  closeLoginModal () {
    this.setData({ showLoginModal: false });
  },

  // 检查是否已关注作者
  async checkIfFollowing (userId, authorId) {
    try {
      const res = await checkFollow({ userId, authorId });
      if (res.success) {
        this.setData({ isFollowing: res.data });
      }
    } catch (error) {
      console.error('检查关注状态失败:', error);
    }
  },

  // 关注或取关操作
  async toggleFollow () {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }

    const { recipeInfo, isFollowing, userId } = this.data;
    try {
      const data = {
        followerId: userId,
        followeeId: recipeInfo.authorId
      }
      if (isFollowing) {
        const res = await unFollowAuthor(data);
        if (res.success) {
          this.setData({ isFollowing: false });
          wx.showToast({
            title: '已取消关注',
            icon: 'success'
          });
        }
      } else {
        const res = await followAuthor(data);
        if (res.success) {
          this.setData({ isFollowing: true });
          wx.showToast({
            title: '已关注',
            icon: 'success'
          });
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 处理编辑逻辑
  handleEdit () {
    wx.navigateTo({
      url: `/pages/myRecipes/addRecipe/addRecipe?id=${this.data.recipeId}&fromDetail=true`
    });
  },
  // 跳转到用户详情页
  navigateToUserDetail () {
    const { recipeInfo } = this.data;
    if (recipeInfo && recipeInfo.authorId) {
      console.log("跳转到用户详情页，authorId:", recipeInfo.authorId);
      wx.navigateTo({
        url: `/pages/userDetail/userDetail?userId=${recipeInfo.authorId}`
      });
    } else {
      wx.showToast({
        title: '无法获取作者信息',
        icon: 'none'
      });
    }
  },

  // 处理删除逻辑
  handleDelete () {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个菜谱吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });

          try {
            // **1. 先删除数据库中的菜谱**
            const deleteRes = await deleteRecipe(this.data.recipeId);
            if (!deleteRes.success) {
              wx.showToast({ title: deleteRes.message || '删除失败', icon: 'none' });
              return;
            }

            // **2. 组装需要删除的云存储文件列表**
            const { recipeInfo } = this.data;
            let fileList = [];

            if (recipeInfo.coverUrl) fileList.push(recipeInfo.coverUrl);
            if (recipeInfo.steps && recipeInfo.steps.length > 0) {
              recipeInfo.steps.forEach(step => {
                if (step.imageUrl) fileList.push(step.imageUrl);
              });
            }

            console.log('需要删除的图片列表:', fileList);

            // **3. 删除云端图片（如果有）**
            if (fileList.length > 0) {
              await wx.cloud.deleteFile({ fileList });
              console.log('图片删除成功');
            }

            // **4. 删除成功，返回上一页**
            wx.showToast({ title: '删除成功', icon: 'success' });
            setTimeout(() => wx.navigateBack(), 1000);
          } catch (error) {
            console.error('删除失败:', error);
            wx.showToast({ title: '删除失败', icon: 'none' });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },
  // 处理评论数据
  processCommentsData (comments) {
    return comments.map(comment => ({
      ...comment,
      date: this.formatDate(comment.createdAt),
      likes: comment.likeCount || 0,
      isLiked: comment.isLiked || false,
      replyCount: comment.replyCount || 0,
      showReplies: false, // 默认不展开回复
      replies: [], // 初始化空的回复数组
      isTemporary: false, // 默认不是临时评论
    }));
  },
  // 获取评论的回复
  async loadRepliesForComment (commentId) {
    try {
      // wx.showLoading({ title: '加载回复中...' });

      const res = await getRepliesByCommentId(commentId);

      if (res.success && res.data) {
        // 处理回复数据
        const replies = this.processCommentsData(res.data);

        // 为每个回复添加isReplyToParent标记
        const parentComment = this.data.comments.find(c => c.commentId === commentId);
        const processedReplies = replies.map(reply => {
          // 如果回复的是父评论作者，标记为回复父评论
          const isReplyToParent = reply.replyToUserId === parentComment.userId;
          return {
            ...reply,
            isReplyToParent,
            isLiked: false // 默认设置为未点赞
          };
        });
        // 无论是否登录，都获取子评论点赞数量
        for (let i = 0; i < processedReplies.length; i++) {
          try {
            // 获取点赞数量
            const countRes = await getLikeCount({
              commentId: processedReplies[i].commentId
            });

            if (countRes.success) {
              processedReplies[i].likes = countRes.data;
            }

            // 如果用户已登录，检查点赞状态
            if (this.data.userId) {
              const likeRes = await getLikeStatus({
                userId: this.data.userId,
                commentId: processedReplies[i].commentId
              });

              if (likeRes.success) {
                processedReplies[i].isLiked = likeRes.data;
              }
            }
          } catch (error) {
            console.error('获取子评论点赞信息失败:', error);
          }
        }
        // 更新评论列表中的回复
        const updatedComments = this.data.comments.map(c => {
          if (c.commentId === commentId) {
            return { ...c, replies: processedReplies };
          }
          return c;
        });

        this.setData({ comments: updatedComments });
      } else {
        console.error('获取回复失败:', res);
      }
    } catch (error) {
      console.error('获取回复失败:', error);
      wx.showToast({ title: '获取回复失败', icon: 'none' });
    }
  },
  // 获取评论列表（一级评论）
  async fetchComments (recipeId) {
    try {
      // wx.showLoading({ title: '加载评论中...' });

      const res = await getCommentsByRecipeId(recipeId);

      if (res.success) {
        // 处理评论数据
        const comments = this.processCommentsData(res.data);
        // 无论是否登录，都获取点赞数量
        for (let i = 0; i < comments.length; i++) {
          try {
            // 获取点赞数量
            const countRes = await getLikeCount({
              commentId: comments[i].commentId
            });

            if (countRes.success) {
              comments[i].likes = countRes.data;
            }

            // 如果用户已登录，检查点赞状态
            if (this.data.userId) {
              const likeRes = await getLikeStatus({
                userId: this.data.userId,
                commentId: comments[i].commentId
              });

              if (likeRes.success) {
                comments[i].isLiked = likeRes.data;
              }
            } else {
              // 未登录状态下，默认设置为未点赞
              comments[i].isLiked = false;
            }
          } catch (error) {
            console.error('获取点赞信息失败:', error);
          }
        }
        this.setData({ comments });
        // 计算总评论数（包括回复）
        this.calculateTotalCommentCount();
        //此处不获取回复数据，按需加载
      } else {
        console.error('获取评论失败:', res);
        wx.showToast({ title: res.message || '获取评论失败', icon: 'none' });
      }
      wx.hideLoading();
    } catch (error) {
      console.error('获取评论失败:', error);
      wx.hideLoading();
      wx.showToast({ title: '获取评论失败', icon: 'none' });
    }
  },
  // 计算总评论数（父级评论 + 子级回复）
  calculateTotalCommentCount () {
    const { comments } = this.data;
    let totalCount = comments.length;

    // 加上所有回复的数量
    comments.forEach(comment => {
      totalCount += comment.replyCount || 0;
    });

    this.setData({ totalCommentCount: totalCount });
  },
  // 切换评论回复的展开/折叠状态
  toggleReplies (e) {
    const { id } = e.currentTarget.dataset;
    const { comments } = this.data;

    // 找到当前评论
    const commentIndex = comments.findIndex(c => c.commentId === id);
    if (commentIndex === -1) return;

    const comment = comments[commentIndex];
    const showReplies = !comment.showReplies;

    // 更新评论的展开状态
    const updatedComments = [...comments];
    updatedComments[commentIndex] = {
      ...comment,
      showReplies
    };

    this.setData({ comments: updatedComments });

    // 如果是展开状态且还没有加载回复，则加载回复
    if (showReplies && (!comment.replies || comment.replies.length === 0)) {
      this.loadRepliesForComment(id);
    }
  },
  // 移除临时评论或回复
  removeTemporaryComment (replyToId) {
    if (replyToId) {
      // 移除临时回复
      const updatedComments = this.data.comments.map(c => {
        if (c.commentId === replyToId) {
          return {
            ...c,
            replies: (c.replies || []).filter(r => !r.isTemporary),
            replyCount: c.replyCount - 1
          };
        }
        return c;
      });
      this.setData({ comments: updatedComments });
    } else {
      // 移除临时评论
      this.setData({
        comments: this.data.comments.filter(c => !c.isTemporary)
      });
    }
  },

  async refreshComments () {
    const { recipeId, comments } = this.data;

    // 保存当前已展开评论的ID
    const expandedCommentIds = comments
      .filter(comment => comment.showReplies)
      .map(comment => comment.commentId);

    setTimeout(async () => {
      try {
        const res = await getCommentsByRecipeId(recipeId);
        if (res.success) {
          // 处理新获取的评论数据
          const newComments = this.processCommentsData(res.data);

          // 恢复展开状态
          const updatedComments = newComments.map(comment => {
            // 如果评论之前是展开的，保持展开状态
            if (expandedCommentIds.includes(comment.commentId)) {
              return {
                ...comment,
                showReplies: true
              };
            }
            return comment;
          });

          this.setData({ comments: updatedComments });

          // 对于已展开的评论，重新加载其回复
          expandedCommentIds.forEach(commentId => {
            const comment = updatedComments.find(c => c.commentId === commentId);
            if (comment && (!comment.replies || comment.replies.length === 0)) {
              this.loadRepliesForComment(commentId);
            }
          });
        }
      } catch (error) {
        console.error('刷新评论失败:', error);
      }
    }, 1000);
  },


  // 格式化日期
  formatDate (timestamp) {
    if (!timestamp) return '';

    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;

    // 小于1分钟
    if (diff < 60 * 1000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 60 * 60 * 1000) {
      return Math.floor(diff / (60 * 1000)) + '分钟前';
    }
    // 小于24小时
    if (diff < 24 * 60 * 60 * 1000) {
      return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
    }
    // 小于30天
    if (diff < 30 * 24 * 60 * 60 * 1000) {
      return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
    }

    // 超过30天显示具体日期
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  },

  // 评论输入处理
  onCommentInput (e) {
    this.setData({ commentText: e.detail.value });
  },
  // 添加点赞评论方法
  async likeComment (e) {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }
    const { id } = e.currentTarget.dataset;
    const { userId, comments } = this.data;

    if (!userId) {
      this.setData({ showLoginModal: true });
      return;
    }

    try {
      // 找到当前评论
      const commentIndex = comments.findIndex(c => c.commentId === id);
      if (commentIndex === -1) return;

      const comment = comments[commentIndex];
      const isLiked = !comment.isLiked;

      // 乐观更新UI
      const updatedComments = [...comments];
      updatedComments[commentIndex] = {
        ...comment,
        isLiked,
        likes: isLiked ? (comment.likes + 1) : (comment.likes - 1)
      };

      this.setData({ comments: updatedComments });

      // 调用API
      const data = {
        userId,
        recipeId: this.data.recipeId,
        commentId: id
      };

      const res = isLiked
        ? await like(data)
        : await unlike(data);

      if (!res.success) {
        // 如果API调用失败，回滚UI状态
        updatedComments[commentIndex] = comment;
        this.setData({ comments: updatedComments });
        wx.showToast({ title: '操作失败', icon: 'none' });
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      wx.showToast({ title: '操作失败', icon: 'none' });
    }
  },
  // 子评论点赞功能
  async likeReply (e) {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }
    const { id, parentId } = e.currentTarget.dataset;
    const { userId, comments } = this.data;

    if (!userId) {
      this.setData({ showLoginModal: true });
      return;
    }

    try {
      // 找到父评论和子评论
      const parentIndex = comments.findIndex(c => c.commentId === parentId);
      if (parentIndex === -1) return;

      const parent = comments[parentIndex];
      const replyIndex = parent.replies.findIndex(r => (r.commentId === id || r._id === id));
      if (replyIndex === -1) return;

      const reply = parent.replies[replyIndex];
      const isLiked = !reply.isLiked;

      // 乐观更新UI
      const updatedComments = [...comments];
      const updatedReplies = [...parent.replies];
      updatedReplies[replyIndex] = {
        ...reply,
        isLiked,
        likes: isLiked ? (reply.likes + 1) : (reply.likes - 1)
      };

      updatedComments[parentIndex] = {
        ...parent,
        replies: updatedReplies
      };

      this.setData({ comments: updatedComments });

      // 调用API - 使用与父评论相同的接口
      const data = {
        userId,
        commentId: id
      };

      const res = isLiked
        ? await like(data)
        : await unlike(data);

      if (!res.success) {
        // 如果API调用失败，回滚UI状态
        updatedReplies[replyIndex] = reply;
        updatedComments[parentIndex] = {
          ...parent,
          replies: updatedReplies
        };
        this.setData({ comments: updatedComments });
        wx.showToast({ title: '操作失败', icon: 'none' });
      }
    } catch (error) {
      console.error('子评论点赞操作失败:', error);
      wx.showToast({ title: '操作失败', icon: 'none' });
    }
  },
  // 显示对回复的回复输入框
  showReplyToReply (e) {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }
    const { parentId, replyId, author } = e.currentTarget.dataset;
    const comment = this.data.comments.find(c => c.commentId === parentId);

    if (parentId && comment) {
      // 找到被回复的回复
      const reply = comment.replies.find(r => r._id === replyId || r.commentId === replyId);

      if (reply) {
        // 检查是否是用户自己的评论
        if (reply.userId === this.data.userId) {
          // 如果是自己的评论，弹出删除确认框
          this.showDeleteConfirm(parentId, replyId);
        } else {
          // 如果不是自己的评论，设置回复状态
          this.setData({
            replyToId: parentId, // 仍然是父评论ID
            replyToUserId: reply.userId, // 被回复用户ID
            replyToUsername: author || '用户', // 被回复用户名称
            isReplyToParent: false, // 标记为回复子评论
            commentText: '' // 清空输入框内容
          });

          wx.pageScrollTo({
            selector: '.comment-input',
            duration: 300
          });
        }
      }
    }
  },
  async submitComment () {
    const { commentText, recipeId, userId, replyToId, replyToUserId, userInfo, comments } = this.data;
    if (!commentText.trim()) {
      wx.showToast({ title: '评论内容不能为空', icon: 'none' });
      return;
    }
    if (!userId) {
      this.setData({ showLoginModal: true });
      return;
    }
    wx.showLoading({ title: '发送中...' });

    // 生成临时ID
    const tempId = 'temp_' + new Date().getTime();

    // 构建临时评论数据
    const tempComment = {
      commentId: tempId,
      userId,
      username: userInfo.username || '用户',
      avatarUrl: userInfo.avatarUrl || '/assets/images/user/avatar.png',
      content: commentText,
      date: '刚刚',
      replyCount: 0,
      isTemporary: true
    };

    // 如果是回复评论，更新原评论的回复列表
    if (replyToId) {
      const updatedComments = comments.map(c => {
        if (c.commentId === replyToId) {
          const tempReply = {
            _id: tempId,
            userId,
            username: userInfo.username || '用户',
            avatarUrl: userInfo.avatarUrl || '/images/default-avatar.png',
            content: commentText,
            date: '刚刚',
            isTemporary: true,
            replyToUserId,
            replyToUsername: this.data.replyToUsername,
            isReplyToParent: isReplyToParent // 添加标记是否回复父评论
          };

          return {
            ...c,
            replyCount: (c.replyCount || 0) + 1,
            replies: c.replies ? [tempReply, ...c.replies] : [tempReply],
            showReplies: true // 自动展开回复区域
          };
        }
        return c;
      });

      this.setData({ comments: updatedComments });

      // 如果父评论之前未展开或没有加载回复，则加载回复
      const parentComment = updatedComments.find(c => c.commentId === replyToId);
      if (parentComment && (parentComment.replies.length === 1 || parentComment.replies.every(r => r.isTemporary))) {
        // 延迟加载回复，确保临时回复先显示
        setTimeout(() => {
          this.loadRepliesForComment(replyToId);
        }, 300);
      }
    } else {
      this.setData({ comments: [tempComment, ...comments] });
    }

    try {
      // 构建评论数据
      const commentData = {
        userId,
        recipeId,
        content: commentText,
        createdAt: new Date()
      };

      // 如果是回复评论，添加父评论ID和被回复用户ID
      if (replyToId) {
        commentData.parentId = replyToId;
        commentData.replyToUserId = replyToUserId;
      }

      const res = await addComment(commentData);

      if (res.success) {
        this.setData({
          commentText: '',
          replyToId: null,
          replyToUserId: null,
          replyToUsername: ''
        });

        // 更新总评论数
        this.calculateTotalCommentCount();

        // // 如果是新评论，静默刷新评论列表
        if (replyToId) {
          // 如果是回复评论，重新加载该父评论的所有回复
          setTimeout(() => {
            this.loadRepliesForComment(replyToId);
          }, 300);
        } else {
          // 如果是新评论，重新加载所有评论
          setTimeout(() => {
            this.fetchComments(this.data.recipeId);
          }, 300);
        }
      } else {
        wx.showToast({ title: '评论失败', icon: 'none' });
        this.removeTemporaryComment(replyToId);
      }
    } catch (error) {
      console.error('评论失败:', error);
      wx.showToast({ title: '评论失败', icon: 'none' });
      this.removeTemporaryComment(replyToId);
    }

    wx.hideLoading();
  },
  // 显示回复输入框 (回复父评论)
  showReplyInput (e) {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      this.setData({ showLoginModal: true });
      return;
    }

    const { id, author } = e.currentTarget.dataset;
    const comment = this.data.comments.find(c => c.commentId === id);

    if (id && comment) {
      // 检查是否是用户自己的评论
      console.log(comment.userId, this.data.userId);
      console.log(comment.userId === this.data.userId);

      if (comment.userId === this.data.userId) {
        // 如果是自己的评论，弹出删除确认框
        this.showDeleteConfirm(id, null);
      } else {
        // 如果不是自己的评论，设置回复状态
        this.setData({
          replyToId: id,
          replyToUserId: comment.userId,
          replyToUsername: author || '用户',
          isReplyToParent: true, // 标记为回复父评论
          commentText: '' // 清空输入框内容
        });

        wx.pageScrollTo({
          selector: '.comment-input',
          duration: 300
        });
      }
    }
  },

  // 显示删除确认对话框
  showDeleteConfirm (parentId, replyId) {
    wx.showModal({
      title: '删除评论',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          console.log('删除评论:', parentId, replyId);
          this.delComment(parentId, replyId);
        }
      }
    });
  },
  // 删除评论
  async delComment (parentId, replyId) {
    console.log('删除评论11111：', parentId, ":", replyId);

    try {
      wx.showLoading({ title: '删除中...' });

      // 确定要删除的评论ID
      const commentId = replyId || parentId;
      const data = {
        commentId,
        userId: this.data.userId,
        recipeId: this.data.recipeId
      };
      // 调用删除评论的API
      const res = await deleteComment(data);
      if (res.success) {
        // 如果是回复评论，只需要重新加载该父评论的回复
        if (replyId) {
          // 先在UI上移除该回复（立即反馈）
          const updatedComments = this.data.comments.map(c => {
            if (c.commentId === parentId) {
              return {
                ...c,
                replies: c.replies.filter(r => (r._id !== replyId && r.commentId !== replyId)),
                replyCount: c.replyCount - 1
              };
            }
            return c;
          });
          this.setData({ comments: updatedComments });

          // 然后重新加载该父评论的所有回复
          setTimeout(() => {
            this.loadRepliesForComment(parentId);
          }, 300);
        } else {
          // 如果是删除父评论，先在UI上移除（立即反馈）
          const updatedComments = this.data.comments.filter(c => c.commentId !== parentId);
          this.setData({ comments: updatedComments });

          // 然后重新加载所有评论
          setTimeout(() => {
            this.fetchComments(this.data.recipeId);
          }, 300);
        }

        // 更新总评论数
        this.calculateTotalCommentCount();

        wx.showToast({ title: '删除成功', icon: 'success' });
      } else {
        wx.showToast({ title: '删除失败', icon: 'none' });
      }
    } catch (error) {
      console.error('删除评论失败:', error);
      wx.showToast({ title: '删除失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },
});
